#include "user_table.h"
#include <stdlib.h>
#include <func.h>
#include "cmd_tast.h"

int sub_click(User_table* ut);

//初始化用户超时表
User_table* User_table_init(void){
    User_table* ut = (User_table*)calloc(1,sizeof(User_table));
    
    for(int i = 0;i<WAIT_TIME;i++){
        user_node* node = (user_node*)malloc(sizeof(user_node));
        node->next = NULL;
        node->prev = NULL;
        node->user_fd = -1;
        ut->arr[i] = node;
    }
    ut->hash_table = (HashTable*)malloc(sizeof(HashTable));
    initHashTable(ut->hash_table);
    return ut;
}
//插入新用户
int User_table_insert(User_table* ut,int fd){
    pthread_mutex_lock(&ut->mutex);
    int click = sub_click(ut);
    user_node* node = (user_node*)calloc(1,sizeof(user_node));
    node->user_fd = fd;

    node->next = ut->arr[click]->next;
    ut->arr[click]->next = node;
    node->prev = ut->arr[click];
    
    KeyValue* val = (KeyValue*)calloc(1,(sizeof(KeyValue)));
    sprintf(val->key,"%d",fd);
    val->value = (void*)node;
    insert(ut->hash_table,val->key,val->value);
    pthread_mutex_unlock(&ut->mutex);

    return 0;
}
//用户发送了信息
int User_table_renew(User_table* ut,int fd){
    pthread_mutex_lock(&ut->mutex);
    char key[50];
    memset(key,0,50);
    sprintf(key,"%d",fd);
    int click = sub_click(ut);
    user_node* node = (user_node*)find(ut->hash_table,key);
    
    node->prev->next = node->next;

    node->prev = NULL;
    node->next = NULL;

    node->next = ut->arr[click]->next;
    ut->arr[click]->next = node;
    node->prev = ut->arr[click];

    pthread_mutex_unlock(&ut->mutex);

    return 0;
}
//断开连接
int User_table_close(User_table* ut){
    pthread_mutex_lock(&ut->mutex);
    user_node* p = ut->arr[ut->click]->next;
    user_node* p_1;
    cmd_tast t;
    t.cmdType = CMD_TYPE_REPLY;
    strcpy(t.content,"[System]长时间未操作，已断开连接");
    t.peerfd = 0;
    while(p != NULL){
        p_1 = p;
        p = p->next;
        send(p_1->user_fd,(char*)&t,sizeof(t),0);
        printf("User%d closed\n",p_1->user_fd);
        close(p_1->user_fd);
        char key[50];
        memset(key,0,50);
        sprintf(key,"%d",p_1->user_fd);

        erase(ut->hash_table,key);
    }
    ut->arr[ut->click]->next = NULL;
    pthread_mutex_unlock(&ut->mutex);
    return 0;
} 

int sub_click(User_table* ut){
    int click = ut->click;
    if(click != 0){
        return click-1;
    }else{
        return WAIT_TIME-1;
    }
}



